<template>
	<hyb-page :title="$store.state.base.hyzx_title">
		<!-- 请开始您的开发 ~ -->
		<template v-slot:body>
			<view class="gui-list gui-padding" :style="{'background':$store.state.base.qjcolor}">
				<view class="gui-list-items" style="height: 120rpx;">
					<gui-image @tap="toInfo" borderRadius="50%" :width="120" :height="120"
						:src="userinfo.u_thumb?userinfo.u_thumb:$store.state.base.erweima" mode="widthFix">
					</gui-image>
					<view class="gui-list-body">
						<view class="gui-list-title">

							<text @tap="toInfo" v-if="$store.state.userinfo"
								class="gui-list-title-text gui-color-white">{{userinfo.u_name?userinfo.u_name:'创建昵称'}}</text>
							<text v-else @tap="toInfo" class="gui-list-title-text gui-color-white">点击登录</text>
							<gui-tags :padding="30" v-if="userinfo.huiyuan"
								:customClass="['gui-bg-white', 'gui-color-black']" :text="userinfo.huiyuan.h_name"
								:borderRadius="50">
							</gui-tags>
							<gui-tags :padding="30" v-if="userinfo.role == 6"
								:customClass="['gui-bg-white', 'gui-color-black']" :text="'企业单位'" :borderRadius="50">
							</gui-tags>
							<!-- <navigator open-type="redirect" v-if="$store.state.base.show_base.hyzx_syjc"
								url="/hyb_o2o/shouce/index/index?type=yh" style="margin-right: -22px;">
								<text class="gui-icons gui-block gui-text gui-padding-x"
									style="font-size: 30rpx;color:#ffffff;">使用教程</text>
							</navigator> -->
						</view>
						<text v-if="userinfo.huiyuan" class="gui-color-white gui-flex gui-row gui-margin-top">
							<text
								class="gui-list-title-text gui-color-white">会员到期时间：{{userinfo.u_typeendtime.substr(0,10)}}</text>
						</text>
					</view>
					<text v-if="$store.state.base.show_base.hyzx_syjc"
						class="gui-list-arrow-right gui-icons gui-color-white">&#xe601;</text>
				</view>
			</view>

			<!-- #ifdef MP -->
			<official-account v-if="$store.state.userinfo && !$store.state.userinfo.openid"></official-account>
			<!-- #endif -->

			<view
				class="gui-block gui-margin-x-small gui-margin-top-middle gui-border-radius-large gui-overflow-hidden gui-bg-white ">
				<gui-box-banner :items="items" @taped="bannerTap"></gui-box-banner>
			</view>

			<view v-if="$store.state.base.show_base.hyzx_ys" style="margin-top: 5rpx;">
				<view class="gui-margin-top-middle gui-margin-x-middle gui-bg-white gui-border-radius-large"
					v-for="(menu,title) in menus" :key="title">
					<view class="gui-padding-middle gui-border-b gui-h5 gui-bold gui-color-gray"
						style="font-size: 30rpx;">{{title}}</view>
					<view @tap="menuTab(menu1)" class="gui-list" v-for="(menu1,index1) in menu" :key="index1">
						<view class="gui-list-items  gui-padding-middle gui-padding-y-middle gui-border-b">
							<image mode="aspectFit" :src="menu1.thumb" style="width: 50rpx;height: 50rpx;"></image>
							<view class="gui-list-body ">
								<view class="gui-list-title">
									<view class="gui-flex gui-align-items-center">
										<text class="gui-list-title-text"
											style="font-size: 36rpx;">{{menu1.title}}</text>
										<text class="gui-text-small gui-color-red gui-margin-x"></text>
									</view>

								</view>
							</view>
							<text class="gui-list-arrow-right gui-icons gui-color-gray">&#xe601;</text>
						</view>
					</view>
				</view>
			</view>

			<hyb-grid v-else :titleClass="['gui-bold']"
				class="gui-bg-white gui-block gui-margin-x-small gui-margin-top-middle gui-border-radius-large gui-overflow-hidden"
				:columns="4" :items="menu" :keys="['thumb','title']" @item_click="menuTab" :key="title"
				v-for="(menu,title) in menus" :title="title">
			</hyb-grid>

			<view v-if="base.banquan_isshow" style="margin-top: 10rpx;" class="gui-ic-banquan gui-padding">
				<text class="gui-ic-banquan">{{base.banquan}}</text>
			</view>
			<view v-else style="height: 0.01rpx;"></view>

			<hyb-location-alert ref="alert" @success="dingwei"></hyb-location-alert>
			<gui-modal ref="daili" :customClass="['gui-bg-white', 'gui-dark-bg-level-3', 'gui-border-radius']"
				title="申请成为代理商">
				<template v-slot:content>
					<view class=" gui-margin">
						<view class="gui-form-item gui-border-b gui-padding">
							<text class="gui-form-label gui-secondary-text">姓名</text>
							<view class="gui-form-body">
								<input class="gui-form-input" v-model="formData.name" placeholder="请输入姓名" />
							</view>
						</view>

						<view class="gui-form-item gui-border-b gui-padding">
							<hyb-phone v-model="formData.phone" :verify="false"></hyb-phone>
						</view>
					</view>
				</template>

				<!-- 利用 flex 布局 可以放置多个自定义按钮哦  -->
				<template v-slot:btns>
					<view class="gui-padding">
						<button type="default" @tap="dialiComfirm()"
							class="gui-button-mini  gui-bg-blue gui-color-white">
							提交信息
						</button>
					</view>
				</template>
			</gui-modal>
		</template>
	</hyb-page>
</template>
<script>
	export default {
		data() {
			return {
				items: [
					[0, '', '余额'],
					[0, '', '积分'],
				],
				menus: [],
				daili: null,
				formData: {
					name: '',
					phone: ''
				}
			}
		},

		computed: {
			base: () => {
				return uni.storage.get("base");
			},
			userinfo: function() {
				return this.$store.getters.getUserinfo();
			}
		},


		watch: {
			userinfo(info) {
				this.items[0][0] = parseFloat(info.u_money).toFixed(2);
				this.items[1][0] = info.u_jifen;
			}
		},

		onShareAppMessage() {
			return {
				title: this.$store.state.base.name
			};
		},

		onShow() {
			if (this.$store.state.userinfo) {
				this.items[0][0] = parseFloat(this.userinfo.u_money).toFixed(2);
				this.items[1][0] = this.userinfo.u_jifen;
			}
			this.getUserInfo()
		},
		onLoad(options) {



			uni.gPost("menu/mine").then((menus) => {
				this.menus = menus;
			})


			// #ifdef MP 
			if (this.$store.state.base.zddy && this.$store.state.userinfo) {
				if (!this.$store.state.userinfo.openid) {
					this.dingyue()
				} else {
					if (!uni.storage.get("dingyue_flag")) {
						uni.gPost("dingyue1").then((subscribe) => {
							if (subscribe == 0) {
								uni.navigateTo({
									url: '/hyb_o2o/dingyue/dingyue1'
								})
							}
						})
					}
				}
			}
			// #endif
			if (this.$store.state.userinfo.u_daili) this.getDaili();
		},
		methods: {
			dialiComfirm() {
				if (this.formData.name.length < 2) {
					uni.showToast({
						title: '姓名格式错误!',
						icon: 'none'
					})
				} else if (!/^1[0-9]{10,10}$/.test(this.formData.phone)) {
					uni.showToast({
						title: '手机号格式错误!',
						icon: 'none'
					})
				} else {
					uni.gPost('daili/save', this.formData).then(() => {
						uni.showToast({
							title: '提交成功'
						})
						this.$refs.daili.close()
						this.getDaili()
					})
				}
			},
			dingyue() {
				uni.navigateTo({
					url: "/hyb_o2o/h5/h5?src=" + encodeURIComponent('https://xjz.cyygkj.cn/' + this.$store
						.state.base.path + '/dingyue1?u_id=' + this.$store.state.userinfo.u_id)
				})
			},
			dingwei(url) {
				let that = this;
				uni.location.getLocation().then((location) => {
					if (location) {
						this.$store.commit("set_location", location);
						if (url) {
							uni.navigateTo({
								url: url
							})
						}
					}
				}).catch((e) => {
					that.$refs.alert.show();
					console.log(e)
				})
			},

			getDaili() {
				uni.gPost("daili/info").then((daili) => {
					this.daili = daili
				})
			},


			getUserInfo() {
				uni.gPost("user/info").then((info) => {
					uni.storage.set("userinfo", info);
					this.$store.commit("set_user", info);
					this.items[0][0] = parseFloat(info.u_money).toFixed(2);
					this.items[1][0] = info.u_jifen;
				})
			},

			menuTab(item) {
				if (item.lianjie == "kefu") {
					uni.makePhoneCall({
						phoneNumber: this.base.phone.split('+')[0]
					})
				} else if (item.lianjie == "user_qrcode") {
					uni.gPost("qrcode", {
						margin: 1,
						size: 300,
						text: this.$store.state.userinfo.u_id
					}).then((res) => {
						uni.previewImage({
							urls: [res]
						})
					})
				} else if (item.lianjie == "exit") {
					this.$store.commit("set_user", null);
					uni.storage.clear("userinfo");
					uni.storage.clear("token");
					uni.storage.clear("accept");
					uni.storage.clear("xieyi");
					uni.storage.clear("dingyue_flag");
					uni.reLaunch({
						url: "/hyb_o2o/index/index?flag=refresh"
					})

				} else if (item.lianjie == "clear") {
					uni.storage.clear("accept");
					uni.gPost("base/info").then((base) => {
						this.$store.commit("set_base", base)
					})
					uni.gPost("menu/tabbar").then((menus) => {
						this.$store.commit("set_menus", menus)
					})
				} else if (item.lianjie == "dingyue") {
					if (this.$store.state.base.zddy) {
						this.dingyue()
					} else {
						uni.navigateTo({
							url: "/hyb_o2o/h5/h5?src=" + encodeURIComponent('https://xjz.cyygkj.cn/' + this.$store
								.state.base.path + '/dingyue1?u_id=' + this.$store.state.userinfo.u_id)
						})
					}

				} else if (item.lianjie.indexOf("http") == 0) {
					uni.navigateTo({
						url: "/hyb_o2o/h5/h5?src=" + encodeURIComponent(item.lianjie)
					})
				} else {

					// #ifdef MP
					// if (this.$store.state.base.show_base && this.$store.state.base.show_base.is_dingwei && this.$store
					// 	.state.location == null) {
					// 	this.dingwei(item.lianjie)
					// 	return;
					// }
					// #endif

					if (item.lianjie == '/hyb_o2o/daili/index/index' && (!this.daili || typeof this.daili == 'string')) {
						// this.$refs.daili.open()
						// return
					}
					uni.navigateTo({
						url: item.lianjie
					})
				}
			},
			call() {
				uni.makePhoneCall({
					phoneNumber: this.base.phone.split('+')[0]
				})
			},

			bannerTap(index) {
				if (index == 0) {
					// 检查是否满足条件：shenhe_uniacid == 1 且用户没有手机号
					const shouldHideWithdraw = this.$store.state.base.show_base &&
						this.$store.state.base.show_base.shenhe_uniacid == 1 &&
						!this.$store.state.userinfo.u_phone;

					// 暂时禁用余额相关功能
					uni.showToast({
						title: '功能暂未开放',
						icon: 'none'
					})
					// if (shouldHideWithdraw) {
					// 	// 不显示提现菜单，只显示余额明细
					// 	uni.navigateTo({
					// 		url: "/hyb_o2o/inner/pages/balance/balance?tag=yh"
					// 	})
					// } else {
					// 	// 正常显示提现和余额明细选项
					// 	uni.showActionSheet({
					// 		itemList: ["提现", "余额明细"],
					// 		success: (res) => {
					// 			if (res.tapIndex == 0) {
					// 				uni.navigateTo({
					// 					url: "/hyb_o2o/tixian/tixian?tag=yh"
					// 				})
					// 			} else if (res.tapIndex == 1) {
					// 				uni.navigateTo({
					// 					url: "/hyb_o2o/inner/pages/balance/balance?tag=yh"
					// 				})
					// 			}
					// 		}
					// 	})
					// }
				}
			},

			toYuanGong() {
				uni.gPost("yuangong/info", {}).then((res) => {
					if (res.result == 0) {
						uni.showModal({
							title: "申请入驻",
							content: "您还没有入驻，是否申请入驻?",
							success: (res) => {
								if (res.confirm) {
									uni.gJs.navigate("/hyb_o2o/jishi/ruzhu/ruzhu");
								}
							}
						})
					} else {
						if (res.y_styles == "待审核") {
							uni.showModal({
								title: "审核中",
								content: "您信息还在审核中，是否进行修改?",
								success: (res) => {
									if (res.confirm) {
										uni.gJs.navigate("/hyb_o2o/jishi/ruzhu/ruzhu");
									}
								}
							})
							return;
						} else {
							uni.gJs.navigate("/hyb_o2o/jishi/mine/mine");
						}

					}
				})
			},
			exit() {
				uni.storage.clear("userinfo");
				uni.storage.clear("token");
				uni.reLaunch({
					url: "/hyb_o2o/index/index"
				})
			},

			to(url) {
				uni.gJs.navigate(url);
			},

			toInfo() {
				// **新增判断：若 uniacid === 1，直接跳转，不检查登录状态**
				if (this.$store.state.base.uniacid === 1) {
					return uni.gJs.navigate("/hyb_o2o/user/info/info");
				}

				// 原强制登录逻辑（uniacid 不等于 1 时生效）
				if (this.userinfo.u_id > 0) {
					uni.gJs.navigate("/hyb_o2o/user/info/info");
				} else {
					// 抖音小程序直接使用抖音登录，不跳转到登录页面
					// #ifdef MP-TOUTIAO
					this.douyinDirectLogin();
					// #endif
					
					// #ifndef MP-TOUTIAO
					uni.gJs.navigate("/hyb_o2o/login/login");
					// #endif
				}
			},
			onChooseAvatar(e) {
				console.log(e.detail)
			},


			chooseThumb() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						console.log(res)
					}
				})
			},

			// 抖音直接登录方法
			douyinDirectLogin() {
				let that = this;
				
				// 先获取登录code
				uni.login({
					provider: 'toutiao',
					success: function(loginRes) {
						console.log('抖音登录成功:', loginRes);
						let code = loginRes.code;
						
						// 获取用户信息，这会弹出授权弹窗
						uni.getUserProfile({
							desc: '用于完善用户资料',
							success: function(userRes) {
								console.log('获取用户信息成功:', userRes);
								
								uni.showLoading({
									title: '登录中...',
									mask: true
								});
								
								// 发送到后端
								uni.gPost("mp/login", {
									f_parentid: uni.storage.get("f_parentid"),
									code: code,
									platform: 'douyin',
									userInfo: userRes.userInfo
								}).then((res) => {
									uni.hideLoading();
									console.log('抖音登录响应:', res);
									uni.storage.set("openid", res.openid);
									if (res.token) {
										// 登录成功，保存用户信息
										uni.storage.set("token", res.token);
										uni.storage.set("userinfo", res.userinfo);
										that.$store.commit("set_user", res.userinfo);
										
										uni.showToast({
											title: "抖音登录成功",
											icon: "success"
										});
										
										// 登录成功后跳转到用户信息页面
										setTimeout(() => {
											uni.gJs.navigate("/hyb_o2o/user/info/info");
										}, 1000);
									} else {
										// 登录失败，显示错误信息
										uni.showToast({
											title: "登录失败，请重试",
											icon: "none"
										});
									}
								}).catch((error) => {
									uni.hideLoading();
									console.error('抖音登录错误:', error);
									uni.showToast({
										title: "登录失败，请重试",
										icon: "none"
									});
								});
							},
							fail: function(error) {
								console.error('获取用户信息失败:', error);
								uni.showToast({
									title: "需要授权才能登录",
									icon: "none"
								});
							}
						});
					},
					fail: function(error) {
						console.error('抖音登录失败:', error);
						uni.showToast({
							title: "抖音登录失败",
							icon: "none"
						});
					}
				});
			}
		}
	}
</script>
<style scoped>
	.gui-list-title-text {
		font-size: 32rpx;
	}

	.gui-grid-item {
		padding: 20rpx 0;
		flex: 1 1 25%;
	}

	.gui-ic-image {
		width: 68rpx;
		height: 68rpx;
		margin-bottom: 10rpx;
	}


	.gui-ic-banquan {
		width: 100%;
		text-align: center;
		margin-top: 200rpx;
	}

	.avatar-wrapper {
		background: none;
		padding: 0;
		border: none;
	}

	.avatar-wrapper::after {
		border: none;
	}
</style>